let app = getApp();
let richText = null;  //富文本编辑器实例
let answer = null; //解决方案富文本编辑器实例
const circleMedias = new Array();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        TabCur: 0,
        scrollLeft:0,
        show: {

        },
        getTagsShow: false,
        readOnly: false, //编辑器是否只读
        placeholder: '开始编辑问题内容吧...',
        question:{
            detail:'',
            tagIds:["1","2"]
        },
        answer:{
            detail: ''
        },
        title: '',
        userInfo: null,
        hasAnswer: false,
        richTextId:'#question',
        answerTitle:'',
        tagKeyword:'',
        tags1: null,
        questionPublishShow: true,
        circleMedias:[],
        imgList: [],
        circleDetail: '',
        video: null,
        videoImage: null,
        circle: null,
        authority: ''
    },

    tabBar(){
        if(typeof this.getTabBar === 'function' && this.getTabBar()){
            this.getTabBar().setData({
                selected: 2
            })
        }
    },
    tabSelect(e) {
        this.setData({
            TabCur: e.currentTarget.dataset.id,
            scrollLeft: (e.currentTarget.dataset.id-1)*60
        });
        if (e.currentTarget.dataset.id == 0) {
            this.setData({
                questionPublishShow: true
            });
        } else if (e.currentTarget.dataset.id == 1) {
            this.setData({
                questionPublishShow: false
            });
        }
    },
    onClose(event) {
        let tags1 = this.data.tags1;
    },
    getTagsClose(){
        this.setData({
            getTagsShow: false
        });
    },
    onTagsChange(event){
        this.setData({
            "question.tagIds": event.detail
        });
        let that = this;
        wx.request({
            url: app.globalData.serverUrl + 'dict/getTagByIds',
            method: 'post',
            data: JSON.stringify(that.data.question.tagIds),
            success: function (res){
                console.log(res.data.data)
                that.setData({
                    tags1: res.data.data.tags
                })
            }
        })
    },
    toggle(event) {
        console.log(event.currentTarget.dataset)
        const { index } = event.currentTarget.dataset;
        const checkbox = this.selectComponent(`.checkboxes-${index}`);
        checkbox.toggle();
    },

    noop() {},

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },
    toLogin: function (){
        wx.navigateTo({
            url: '../login/login'
        });
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            userInfo: app.globalData.userInfo
        })
        // TODO 判断用户登录态
        // if (this.data.userInfo == null){
        //     this.toLogin();
        // }
        let that = this;
        if (that.data.hasAnswer){
            this.setData({
                'question.status': 1
            });
        } else {
            this.setData({
                richTextId:'#question',
                "answer.detail":null,
                'question.status': 0
            })
        }
        // this.onEditorReady();
        // this.onEditor1Ready();
        console.log(this.data.question.status)
        console.log(that.data.circleMedias)
        this.tabBar();
    },
    isAnswer: function (e) {
        let that = this;
        that.setData({
            "hasAnswer":e.detail.value
        });
        if (that.data.hasAnswer){
            this.setData({
                'question.status': 1
            });
        } else {
            this.setData({
                richTextId:'#question',
                "answer.detail":null,
                'question.status': 0
            })
        }

    },

    // 编辑器初始化完成时触发，可以获取组件实例
    onEditorReady() {
        console.log('[onEditorReady callback]')
        richText = this.selectComponent("#question"); //获取组件实例
    },
    onEditor1Ready(){
        answer = this.selectComponent("#answer"); //获取组件实例
    },

    //设置富文本内容
    setContents(rechtext) {
        this.editorCtx.setContents({
            html: rechtext,
            success: res => {
                console.log('[setContents success]', res)
            }
        })
    },

    //撤销
    undo() {
        console.log('[undo callback]')
    },

    //恢复
    restore() {
        console.log('[restore callback]')
    },

    //清空编辑器内容
    clear() {
        this.editorCtx.clear({
            success: res => {
                console.log("[clear success]", res)
            }
        })
    },

    //清空编辑器事件
    clearBeforeEvent() {
        let that = this;
        console.log('[clearBeforeEvent callback]')
        wx.showModal({
            cancelText: '取消',
            confirmText: '确认',
            content: '确认清空编辑器内容吗？',
            success: (result) => {
                if (result.confirm) {
                    if (that.data.hasAnswer) {
                        answer.clear();
                    } else {
                        richText.clear();
                    }
                }
            },
            fail: (res) => {
            },
        })
    },

    //清空编辑器成功回调
    clearSuccess() {
        console.log('[clearSuccess callback]')
    },

    //清除当前选区的样式
    removeFormat() {
        this.editorCtx.removeFormat();
    },

    //插入图片
    insertImageEvent() {
        let that = this;
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: res => {
                let path = res.tempFilePaths[0];
                //调用子组件方法，图片应先上传再插入，不然预览时无法查看图片。
                        // tempFilePath可以作为img标签的src属性显示图片
                wx.uploadFile({
                    url: app.globalData.serverUrl + 'qiniu', //仅为示例，非真实的接口地址
                    filePath: path,
                    name: 'file',
                    success(res) {
                        let data = JSON.parse(res.data)
                        path = data.data.link;
                        if (that.data.hasAnswer) {
                            answer.insertImageMethod(path).then(res => {
                                console.log('[insert image success callback]=>', res)
                            }).catch(res => {
                                console.log('[insert image fail callback]=>', res)
                            });
                        } else {
                            richText.insertImageMethod(path).then(res => {
                                console.log('[insert image success callback]=>', res)
                            }).catch(res => {
                                console.log('[insert image fail callback]=>', res)
                            });
                        }
                    }
                })
            }
        })
    },

    //保存，获取编辑器内容
    getEditorContent(res) {
        let that = this;
        let {
            value
        } = res.detail;
        wx.showToast({
            title: '获取编辑器内容成功',
            icon: 'none',
        })
        console.log('[getEditorContent callback]=>', value)
        if (that.data.hasAnswer) {
            this.setData({
                "answer.detail" : value.html
            });
        } else {
            this.setData({
                "question.detail" : value.html
            });
        }
        console.log(this.data.question.detail)
        console.log(this.data.answer.detail)
    },

    //show文本工具栏
    showTextTool() {
        this.setData({
            textTool: !this.data.textTool
        })
    },

    //编辑器聚焦时触发
    bindfocus(res) {
        let {
            value
        } = res.detail;
        // console.log('[bindfocus callback]=>', value)
    },

    //编辑器失去焦点时触发
    bindblur(res) {
        let {
            value
        } = res.detail;
        // console.log('[bindblur callback]=>', value)
    },

    //编辑器输入中时触发
    bindinput(res) {
        let {
            value
        } = res.detail;
        // console.log('[bindinput callback]=>', value)
        app.data.richTextContents = value.detail.html;
    },

    //预览富文本
    preview() {
        wx.navigateTo({
            url: `../preview/preview`,
        })
    },
    questionPublish: function () {
        let that = this;
        if (that.data.hasAnswer) {
            this.setData({
                "question.answer.detail": that.data.answer.detail,
                "question.answer.title": that.data.answerTitle
            })
        }
        console.log(this.data.question.status)
        this.setData({
            'question.title': this.data.title
        });
        console.log(this.data.question)
        wx.request({
            url: app.globalData.serverUrl + "question/saveQuestion?username=test",
            method: 'post',
            headers:{
                'content-type':'application/json'
            },
            data: this.data.question,
            success: function (res) {
                wx.switchTab({
                    url: '../question-index/question-index'
                })
                // console.log(res.data);
            }
        });
    },
    getTags:function () {
        this.setData({
            getTagsShow: true
        })
    },
    onTagKeywordChange: function (e) {
        let that = this;
        this.setData({
            tagKeyword: e.detail
        });
        wx.request({
            url: app.globalData.serverUrl + "dict/getTagsBy?keyword="+e.detail,
            method: "get",
            success: function (res){
                let tags = res.data.data.data;
                that.setData({
                    tags: tags
                });
            }
        });
    },

    /**
     * 点滴
     */
    ChooseImage() {
        let that = this;
        wx.chooseImage({
            count: 4, //默认9
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album','camera'], //从相册选择
            success: (res) => {
                if (that.data.imgList.length != 0) {
                    that.setData({
                        imgList: that.data.imgList.concat(res.tempFilePaths)
                    });
                    for (let i = 0; i < res.tempFilePaths.length;i++) {
                        let circleMedia = new Object();
                        wx.uploadFile({
                            url: app.globalData.serverUrl + 'qiniu', //仅为示例，非真实的接口地址
                            filePath: res.tempFilePaths[i],
                            name: 'file',
                            success(res) {
                                let data = JSON.parse(res.data)
                                let path = data.data.link;
                                circleMedia.url = path;
                                circleMedia.remark1 = '0';
                                circleMedias.push(circleMedia);
                            }
                        });
                    }
                } else {
                    that.setData({
                        imgList: res.tempFilePaths
                    });
                    for (let i = 0; i < res.tempFilePaths.length;i++) {
                        let circleMedia = new Object();
                        wx.uploadFile({
                            url: app.globalData.serverUrl + 'qiniu', //仅为示例，非真实的接口地址
                            filePath: res.tempFilePaths[i],
                            name: 'file',
                            success(res) {
                                let data = JSON.parse(res.data)
                                let path = data.data.link;
                                circleMedia.url = path;
                                circleMedia.remark1 = '0';
                                circleMedias.push(circleMedia);
                            }
                        });
                    }

                }
                }
        });
    },
    ChooseVideo() {
        let that = this;
        wx.chooseVideo({
            count: 4, //默认9
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album','camera'], //从相册选择
            compressed: true,
            async: false,
            success: (res) => {
                console.log(res)
                that.setData({
                    videoImage: res.thumbTempFilePath,
                    video: res.tempFilePath
                });
                wx.uploadFile({
                    url: app.globalData.serverUrl + 'qiniu', //仅为示例，非真实的接口地址
                    filePath: res.tempFilePath,
                    name: 'file',
                    async: false,
                    success(res) {
                        let circleMedia = new Object();
                        let data = JSON.parse(res.data)
                        // path = data.data.link;
                        console.log(data.data.link)
                        let path = data.data.link;
                        circleMedia.url = path;
                        circleMedia.remark1 = '1';
                        that.setData({
                            video: data.data.link
                        })
                        circleMedias.push(circleMedia);
                    }
                });
            }
        });
    },
    DelVideo: function () {
        this.setData({
            videoImage: null
        });
    },
    isPublic: function (e) {
        let that = this;
        if (e.detail.value){
            this.setData({
                'authority': 0
            });
        } else {
            this.setData({
                'authority': 1
            })
        }
    },
    circlePublish: function () {
        let that = this;
        let circle = new Object();
        let param = {
            detail: that.data.detail,
        }
        circle.detail = that.data.circleDetail;
        circle.circleMedia = circleMedias;
        // TODO 用户信息
        circle.createBy = '120235415';
        circle.authority = that.data.authority;
        circle.userId = '120235415'
        wx.request({
            url: app.globalData.serverUrl + 'circle',
            method: 'post',
            data: circle,
            success: function (res){
                console.log(res.data.status)
                if (res.data.status == 200){
                    that.setData({
                        imgList: [],
                        video
                    })
                    wx.switchTab({
                        url: '../friend-circle/friend-circle'
                    });

                }

            }
        })
        console.log(JSON.stringify(circle));
        // console.log(circle)
    },
    ViewImage(e) {
        wx.previewImage({
            urls: this.data.imgList,
            current: e.currentTarget.dataset.url
        });
    },
    ViewVideo(e) {
        this.videoContext = wx.createVideoContext('prew_video');
        var status = e.detail.fullScreen;
        var play = {
            playVideo: false
        }
        if (status) {
            play.playVideo = true;
        } else {
            this.videoContext.pause();
        }
        this.setData(play);
    },
    DelImg(e) {
        wx.showModal({
            title: '召唤师',
            content: '确定要删除这段回忆吗？',
            cancelText: '再看看',
            confirmText: '再见',
            success: res => {
                if (res.confirm) {
                    this.data.imgList.splice(e.currentTarget.dataset.index, 1);
                    this.setData({
                        imgList: this.data.imgList
                    })
                }
            }
        })
    },
    // circleViewImage(e) {
    //     wx.previewImage({
    //         urls: this.data.imgList,
    //         current: e.currentTarget.dataset.url
    //     });
    // },
    // circleDelImg(e) {
    //     wx.showModal({
    //         title: '召唤师',
    //         content: '确定要删除这段回忆吗？',
    //         cancelText: '再看看',
    //         confirmText: '再见',
    //         success: res => {
    //             if (res.confirm) {
    //                 this.data.imgList.splice(e.currentTarget.dataset.index, 1);
    //                 this.setData({
    //                     imgList: this.data.imgList
    //                 })
    //             }
    //         }
    //     })
    // },

});
